package utils

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	error2 "insighttracking/common/error"
	"net/http"
)

type Response struct {
	Code    int64       `json:"code"`
	Message string      `json:"message"`
	Result  interface{} `json:"result,omitempty"`
}

func Success(data interface{}) *Response {
	return &Response{
		Code:    0,
		Message: "请求成功",
		Result:  data,
	}
}

func Fail(err *error2.Error, data interface{}) *Response {
	return &Response{
		Code:    err.Code,
		Message: err.Msg,
		Result:  data,
	}
}

func OriginalResponse(code int64, message string, data interface{}) *Response {
	return &Response{
		Code:    code,
		Message: message,
		Result:  data,
	}
}
func OkHandler(_ context.Context, v interface{}) any {
	return Success(v)
}

func ErrHandler(name string) func(ctx context.Context, err error) (int, any) {
	return func(ctx context.Context, err error) (int, any) {
		causeErr := errors.Cause(err)
		fmt.Println("错误信息：", causeErr)
		var errMessage = err.Error()

		translatorError := TranslatorError(err)
		if translatorError != "" {
			errMessage = translatorError
		}
		// 日志记录
		logx.WithContext(ctx).Errorf("【%s】 err %v", name, errMessage)
		var e *error2.Error
		switch {
		case errors.As(err, &e):
			// 自定义一个 错误返回类型
			return http.StatusOK, Fail(e, nil)
		default:
			return http.StatusOK, &Response{
				Code:    1,
				Message: errMessage,
				Result:  nil,
			}
		}
	}
}
